package com.jf.springmvc.filedownload;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-11-02
 * Time:23:58
 */
@RequestMapping("/filed")
@Controller
public class DownLoadController {
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getServletContext().getResourceAsStream("/img/cat.png");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=cat.png");
        HttpStatus status = HttpStatus.OK;
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        ResponseEntity<byte[]> response = new ResponseEntity<>(buffer, headers, status);
        return response;
    }
}
